from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
import tushare as ts
from datetime import datetime


class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow,self).__init__()
        self.initUI()

    def initUI(self):
        contractname = QLabel('ContractName')
        marketdata   = QLabel('MarketData')

        self.contractnameEdit = QLineEdit()
        self.marketdataTable   = QTableView()
        ok           = QPushButton('OK')
        cancel       = QPushButton('Cancel')

        #headerdata = ['date','open','high','close','low','volume','amount']
        self.marketdatamodel = QStandardItemModel(0,7,self)
        self.marketdatamodel.setHeaderData(0,Qt.Horizontal,'date')
        self.marketdatamodel.setHeaderData(1,Qt.Horizontal,'open')
        self.marketdatamodel.setHeaderData(2,Qt.Horizontal,'high')
        self.marketdatamodel.setHeaderData(3,Qt.Horizontal,'close')
        self.marketdatamodel.setHeaderData(4,Qt.Horizontal,'low')
        self.marketdatamodel.setHeaderData(5,Qt.Horizontal,'volume')
        self.marketdatamodel.setHeaderData(6,Qt.Horizontal,'amount')
        self.marketdataTable.setModel(self.marketdatamodel)

        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(contractname,1,0)
        grid.addWidget(self.contractnameEdit,1,1)

        grid.addWidget(marketdata,2,0)
        grid.addWidget(self.marketdataTable,2,1)
        grid.addWidget(ok,3,0)
        grid.addWidget(cancel,3,1)

        self.setLayout(grid)
        self.setWindowTitle('Main')
        self.resize(800,600)

        self.connect(ok,SIGNAL('clicked()'),self.GetMarketData)

    def GetMarketData(self):
        contractname = self.contractnameEdit.text()
        if contractname != '':
            histdata = ts.get_h_data(contractname,start='2016-11-10',end='2016-11-28')
            #print histdata
            i=0
            for index ,row in histdata.iterrows():
                j=0
                Index_DateTime =index.to_pydatetime()#Timestamp --> datetime
                self.marketdatamodel.setItem(i,j,QStandardItem(Index_DateTime.strftime('%Y-%m-%d')))
                j+=1
                for col_name in histdata.columns:
                    content = row[col_name] #content type is numpy.float64
                    #print type(content),content
                    strContent = str(content) #convert to string
                    #print type(strContent),strContent

                    self.marketdatamodel.setItem(i,j,QStandardItem(strContent))
                    j+=1
                i+=1